using System;
using System.Threading.Tasks;
using Vue_AspNetCore_Project.Helper;
using Vue_AspNetCore_Project.Models;
using Vue_AspNetCore_Project.Services;
using Vue_AspNetCore_Project.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

namespace Vue_AspNetCore_Project.Controllers
{

    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")]
    public class AccountController : ControllerBase
    {
        private readonly string REG_KEY = "__register__";
       // private readonly string RESETPWD_KEY = "__resetpassword__";
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IEmailSender _emailSender;
        private readonly ILogger<AccountController> _logger;
        private readonly IWebHostEnvironment _hostingEnvironment;

        private readonly IDistributedCache _distributedCache;
        public AccountController(UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager, IEmailSender emailSender,
            ILogger<AccountController> logger, IWebHostEnvironment hostingEnvironment, IDistributedCache distributedCache)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _emailSender = emailSender;
            _hostingEnvironment = hostingEnvironment;
            _distributedCache = distributedCache;
        }

        [HttpPost("SendValidationCode")]
        [AllowAnonymous]
        public IActionResult SendRegValidationCode([FromForm]string email)
        {

            Console.WriteLine(email);

            var randomCode = GetID();

            string regkey = REG_KEY + email;

            _distributedCache.SetString(regkey, randomCode.ToString(), new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5)));

            _emailSender.SendEmailRegister(email, email, randomCode.ToString(), _hostingEnvironment);

            _logger.LogInformation("注册验证码已发送。");

            var message = "验证码已发送到您的邮箱";

            return Ok(new { success = true, message });

        }

        /// <summary>
        /// 发送密码重置验证码，后台调用。
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("SendResetPasswordValidationCode")]
        [AllowAnonymous]
        public async Task<IActionResult> SendResetPasswordValidationCode(string email)
        {

            var user = await _userManager.FindByEmailAsync(email);

            if (user == null) return Ok(new { success = false, message = "您尚未注册平台账号。" });

            var randomCode = GetID();

            _emailSender.SendEmailResetPassword(email, email, randomCode.ToString(), _hostingEnvironment);

            _logger.LogInformation("重设密码验证码已发送。");

            var message = "验证码已发送到您的邮箱";

            return Ok(new { success = true, message });
        }

        /// <summary>
        /// 获取一个随机的验证码
        /// </summary>
        /// <returns></returns>
        private int GetID()
        {
            Random rd = new Random();
            int num = rd.Next(100000, 999999);
            return num;

        }

        [HttpPost("Register")]
        public async Task<IActionResult> Register([FromBody] RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {

                string s = string.Empty;
                foreach (var ms in ModelState.Values)
                {
                    foreach (var err in ms.Errors)
                    {
                        s += err;
                    }

                }
                return BadRequest(s);

            }
            string key = REG_KEY + model.Email;

            var randomCode = _distributedCache.GetString(key);

            if (string.IsNullOrEmpty(randomCode))
            {
                return BadRequest("验证码已过期");
            }
            else if (randomCode != model.SecurityCode)
            {
                return BadRequest("验证码错误");
            }

            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
                return BadRequest("邮箱已经被注册.");
            user = new ApplicationUser
            {

                Email = model.Email,
                EmailConfirmed = true,
                UserName = model.Email,
                LockoutEnabled = true
            };
            var registerResult = await _userManager.CreateAsync(user, model.Password);
            if (!registerResult.Succeeded)
            {
                string s = string.Empty;
                foreach (var item in registerResult.Errors)
                {
                    s += item.Description;
                }

                return BadRequest(s);
            }

            await _userManager.AddToRoleAsync(user, "CustomerAdmin");
            return Ok();
        }

    }
}